package top.milkbox.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import top.milkbox.controller.LoginController;

/**
 * 有关Http请求的工具类
 */
@Component
public class GuoHttpUtils {

    // SpringBoot提供的Http请求工具类
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeChatSecretCode weChatSecretCode;

    public WeChatInfo getOpenidAndSessionKey(String code) {
        // 设置小程序的id和安全码


        // 发送get请求
        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid=" + weChatSecretCode.getAppId() +
                "&secret=" + weChatSecretCode.getSecret() +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        String weChatInfoJson = forEntity.getBody(); // 获取到数据
        System.out.println("------> weChatInfoJson: " + weChatInfoJson);

        // 将json字符串转换成对象
        ObjectMapper objectMapper = new ObjectMapper();
        WeChatInfo weChatInfo = null;
        try {
            weChatInfo = objectMapper.readValue(weChatInfoJson, WeChatInfo.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println("------> weChatInfo: " + weChatInfo);

        return weChatInfo;
    }

    /**
     * 用来存放Http请求的结果
     */
    @Data
    public static class WeChatInfo {
        private String session_key;
        private String openid;

    }
}
